/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.timesoft.base.register.ctrl;

import com.timesoft.common.bean.ResponseCommon;
import com.timesoft.common.convertor.Base64ConvertorUtils;
import com.timesoft.common.security.SecurityMD5;
import com.timesoft.common.validator.EmailValidator;
import com.timesoft.common.validator.NameValidator;
import com.timesoft.common.validator.PasswordValidator;
import com.timesoft.common.validator.Validator;
import com.timesoft.global.webservice.WebServiceClient;
import com.timesoft.hibernate.bean.Customer;
import com.timesoft.webservice.client.base.BaseWebService;
import com.timesoft.zk.common.ResourceUtil;
import com.timesoft.zk.common.ctrl.IncludePageWsController;
import com.timesoft.zk.common.event.MainEventWsListener;
import com.timesoft.zk.common.generator.CodeStringGenerator;
import com.timesoft.zk.common.generator.Generator;
import com.timesoft.zk.common.message.AlertMessages;
import com.timesoft.zk.common.validator.ValidateManager;
import com.timesoft.zk.common.validator.ValidateUtill;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Html;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;

/**
 *
 * @author sorasaks
 */
public class RegisterListCtrl extends IncludePageWsController {

    private static final Logger LOG = Logger.getLogger(RegisterListCtrl.class);
    private Textbox txtName;
    private Textbox txtLastname;
    private Textbox txtEmail;
    private Textbox txtPassword;
    private Textbox txtRePassword;
    private Html htmlName;
    private Html htmlLastname;
    private Html htmlEmail;
    private Html htmlPassword;
    private Html htmlRePassword;
    private Html htmlAgree;
    private Radiogroup gender;
    private Checkbox chkAgree;
    private Button btnSignup;
    private final BaseWebService baseService;
    private final Base64ConvertorUtils base64;
    private final ValidateManager vmEvent;
    private final ValidateUtill vmUtil;

    public RegisterListCtrl() throws Exception {
        super();
        vmEvent = new ValidateManager();
        vmUtil = new ValidateUtill(contextPath);
        baseService = WebServiceClient.getBaseService();
        base64 = new Base64ConvertorUtils();
    }

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp); //To change body of generated methods, choose Tools | Templates.
        initialEventListener();
    }

    private void initialEventListener() throws Exception {
        txtName.addEventListener(Events.ON_FOCUS, new txtNameEventListener());
        txtName.addEventListener(Events.ON_BLUR, new validateEventListener());

        txtLastname.addEventListener(Events.ON_FOCUS, new txtLastnameEventListener());
        txtLastname.addEventListener(Events.ON_BLUR, new validateEventListener());

        txtEmail.addEventListener(Events.ON_FOCUS, new txtEmailEventListener());
        txtEmail.addEventListener(Events.ON_BLUR, new validateEventListener());

        txtPassword.addEventListener(Events.ON_FOCUS, new txtPasswordEventListener());
        txtPassword.addEventListener(Events.ON_BLUR, new validateEventListener());

        txtRePassword.addEventListener(Events.ON_FOCUS, new txtRePasswordEventListener());
        txtRePassword.addEventListener(Events.ON_BLUR, new validateEventListener());

        chkAgree.addEventListener(Events.ON_CLICK, new validateEventListener());

        btnSignup.addEventListener(Events.ON_CLICK, new btnSignupEventListener());
    }

    private class btnSignupEventListener extends MainEventWsListener implements EventListener {

        public btnSignupEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            if (validate()) {
                Customer customer = new Customer();
                customer.setName(txtName.getValue());
                customer.setLastname(txtLastname.getValue());
                customer.setEmail(txtEmail.getValue());

                SecurityMD5 md5 = new SecurityMD5(txtPassword.getValue());
                customer.setPassword(md5.encoding());
                customer.setGender(((String) gender.getSelectedItem().getValue()).charAt(0));

                CodeStringGenerator codeGen = new CodeStringGenerator(Generator.CUSTOMER_CODE);
                String custCode = codeGen.generateCode();
                customer.setCustomerCode(custCode);

                customer.setActive(Boolean.FALSE);

                ResponseCommon common = (ResponseCommon) base64.stringToGenericObj(baseService.customerCoreSave(
                        base64.genericObjToString(customer),
                        base64.genericObjToString(Executions.getCurrent().getRemoteAddr())));
                Boolean isSave = (Boolean) base64.stringToGenericObj(common.getValue());
                if (!common.isFlag()) {
                    LOG.debug(common.getMessage());
                    AlertMessages.alertMessage(common.getMessage());
                }
                if (isSave) {
                    LOG.info("::::::::::::::::::::::: Active code = " + base64.genericObjToString(customer.getCustomerCode()));

                    AlertMessages.alertMessage("Seccussfully");
                }
            }
        }
    }

    private class txtNameEventListener extends MainEventWsListener implements EventListener {

        public txtNameEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlName.setStyle("display: block;");
            htmlName.setContent(ResourceUtil.getLabel("home.label.register.validate.name", locale));
        }
    }

    private class txtLastnameEventListener extends MainEventWsListener implements EventListener {

        public txtLastnameEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlLastname.setStyle("display: block;");
            htmlLastname.setContent(ResourceUtil.getLabel("home.label.register.validate.lastname", locale));
        }
    }

    private class txtEmailEventListener extends MainEventWsListener implements EventListener {

        public txtEmailEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlEmail.setStyle("display: block;");
            htmlEmail.setContent(ResourceUtil.getLabel("home.label.register.validate.email", locale));
        }
    }

    private class txtPasswordEventListener extends MainEventWsListener implements EventListener {

        public txtPasswordEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlPassword.setStyle("display: block;");
            htmlPassword.setContent(ResourceUtil.getLabel("home.label.register.validate.password", locale));
        }
    }

    private class txtRePasswordEventListener extends MainEventWsListener implements EventListener {

        public txtRePasswordEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlRePassword.setStyle("display: block;");
        }
    }

    private class validateEventListener extends MainEventWsListener implements EventListener {

        public validateEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            Validate(t);
        }
    }

    private void Validate(Event t) throws UnsupportedEncodingException {
        if (t.getTarget().equals(txtName)) {
            Textbox txt = (Textbox) t.getTarget();
            vmEvent.add(vmUtil.require(txt,
                    htmlName,
                    ResourceUtil.getLabel("home.label.register.validate.correct.name", locale),
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

            Validator name = new NameValidator(txt.getValue());
            if (!name.validate()) {
                vmEvent.add(vmUtil.addErrorHtml(htmlName, "Enter name with only charecter of your language."));
            }

        } else if (t.getTarget().equals(txtLastname)) {
            Textbox txt = (Textbox) t.getTarget();
            vmEvent.add(vmUtil.require(txt,
                    htmlLastname,
                    ResourceUtil.getLabel("home.label.register.validate.correct.lastname", locale),
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));
            
            Validator lastname = new NameValidator(txt.getValue());
            if (!lastname.validate()) {
                vmEvent.add(vmUtil.addErrorHtml(htmlLastname, "Enter lastname with only charecter of your language."));
            }
        } else if (t.getTarget().equals(txtEmail)) {
            Textbox txt = (Textbox) t.getTarget();
            vmEvent.add(vmUtil.require(txt,
                    htmlEmail,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

            Validator email = new EmailValidator(txtEmail.getValue());
            if (email.validate()) {
                vmEvent.add(vmUtil.addCorrectHtml(htmlEmail,
                        ResourceUtil.getLabel("home.label.register.validate.correct.email", locale)));
            } else {
                vmEvent.add(vmUtil.addErrorHtml(htmlEmail,
                        ResourceUtil.getLabel("home.label.register.validate.incorrect.email", locale)));
            }
        } else if (t.getTarget().equals(txtPassword)) {
            Textbox txt = (Textbox) t.getTarget();
            vmEvent.add(vmUtil.require(txt,
                    htmlPassword,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

            PasswordValidator password = new PasswordValidator(txtPassword.getValue(), txtRePassword.getValue());
            if (password.validate()) {
                if (password.easyValidate()) {
                    vmEvent.add(vmUtil.addCorrectHtml(htmlPassword,
                            ResourceUtil.getLabel("home.label.register.validate.correct.easy.password", locale)));
                }
                if (password.meduimValidate()) {
                    vmEvent.add(vmUtil.addCorrectHtml(htmlPassword,
                            ResourceUtil.getLabel("home.label.register.validate.correct.meduim.password", locale)));
                }
                if (password.hardValidate()) {
                    vmEvent.add(vmUtil.addCorrectHtml(htmlPassword,
                            ResourceUtil.getLabel("home.label.register.validate.correct.hard.password", locale)));
                }
            } else {
                vmEvent.add(vmUtil.addErrorHtml(htmlPassword,
                        ResourceUtil.getLabel("home.label.register.validate.incorrect.password", locale)));
            }
        } else if (t.getTarget().equals(txtRePassword)) {
            Textbox txt = (Textbox) t.getTarget();
            vmEvent.add(vmUtil.require(txt,
                    htmlRePassword,
                    ""));

            PasswordValidator rePassword = new PasswordValidator(txtPassword.getValue(), txtRePassword.getValue());
            if (rePassword.comparePassword()) {
                vmEvent.add(vmUtil.addCorrectHtml(htmlRePassword,
                        ResourceUtil.getLabel("home.label.register.validate.correct.repassword", locale)));
            } else {
                vmEvent.add(vmUtil.addErrorHtml(htmlRePassword,
                        ResourceUtil.getLabel("home.label.register.validate.incorrect.repassword", locale)));
            }
        } else if (t.getTarget().equals(chkAgree)) {
            Checkbox chk = (Checkbox) t.getTarget();
            vmEvent.add(vmUtil.require(chk,
                    htmlAgree,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.agree", locale)));
        }
    }

    private Boolean validate() throws UnsupportedEncodingException, Exception {
        ValidateManager vm = new ValidateManager();
        vm.add(vmUtil.require(txtName,
                htmlName,
                ResourceUtil.getLabel("home.label.register.validate.correct.name", locale),
                ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

        vm.add(vmUtil.require(txtLastname,
                htmlLastname,
                ResourceUtil.getLabel("home.label.register.validate.correct.lastname", locale),
                ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

        vm.add(vmUtil.require(txtEmail,
                htmlEmail,
                ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

        Validator email = new EmailValidator(txtEmail.getValue());
        if (email.validate()) {
            vm.add(vmUtil.addCorrectHtml(htmlEmail,
                    ResourceUtil.getLabel("home.label.register.validate.correct.email", locale)));
        } else {
            vm.add(vmUtil.addErrorHtml(htmlEmail,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.email", locale)));
        }

        vm.add(vmUtil.require(txtPassword,
                htmlPassword,
                ResourceUtil.getLabel("home.label.register.validate.incorrect.empty", locale)));

        PasswordValidator password = new PasswordValidator(txtPassword.getValue(), txtRePassword.getValue());
        if (password.validate()) {
            if (password.easyValidate()) {
                vm.add(vmUtil.addCorrectHtml(htmlPassword,
                        ResourceUtil.getLabel("home.label.register.validate.correct.easy.password", locale)));
            }
            if (password.meduimValidate()) {
                vm.add(vmUtil.addCorrectHtml(htmlPassword,
                        ResourceUtil.getLabel("home.label.register.validate.correct.meduim.password", locale)));
            }
            if (password.hardValidate()) {
                vm.add(vmUtil.addCorrectHtml(htmlPassword,
                        ResourceUtil.getLabel("home.label.register.validate.correct.hard.password", locale)));
            }
        } else {
            vm.add(vmUtil.addErrorHtml(htmlPassword,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.password", locale)));
        }

        vm.add(vmUtil.require(txtRePassword, htmlRePassword, contextPath + "/img/template/incorrect.png", ""));

        PasswordValidator rePassword = new PasswordValidator(txtPassword.getValue(), txtRePassword.getValue());
        if (rePassword.comparePassword()) {
            vm.add(vmUtil.addCorrectHtml(htmlRePassword,
                    ResourceUtil.getLabel("home.label.register.validate.correct.repassword", locale)));
        } else {
            vm.add(vmUtil.addErrorHtml(htmlRePassword,
                    ResourceUtil.getLabel("home.label.register.validate.incorrect.repassword", locale)));
        }

        vm.add(vmUtil.require(chkAgree, htmlAgree,
                ResourceUtil.getLabel("home.label.register.validate.incorrect.agree", locale)));

        if (!vm.getResult()) {
            return Boolean.FALSE;
        }

        ResponseCommon common = (ResponseCommon) base64.stringToGenericObj(baseService.customerCoreGetCustomerByNameAndLastName(
                base64.genericObjToString(txtName.getValue()),
                base64.genericObjToString(txtLastname.getValue()),
                base64.genericObjToString(null)));
        Customer customer = (Customer) base64.stringToGenericObj(common.getValue());
        if (!common.isFlag()) {
            LOG.debug(common.getMessage());
            AlertMessages.alertMessage(common.getMessage());
        }
        if (customer != null) {
            vm.add(vmUtil.addErrorHtml(htmlName,
                    ResourceUtil.getLabel("home.label.register.validate.duplicate.name", locale)));

            vm.add(vmUtil.addErrorHtml(htmlLastname,
                    ResourceUtil.getLabel("home.label.register.validate.duplicate.lastname", locale)));
            return Boolean.FALSE;
        }

        common = (ResponseCommon) base64.stringToGenericObj(baseService.customerCoreGetCustomerByEmail(
                base64.genericObjToString(txtEmail.getValue()),
                base64.genericObjToString(null)));
        customer = (Customer) base64.stringToGenericObj(common.getValue());
        if (!common.isFlag()) {
            LOG.debug(common.getMessage());
            AlertMessages.alertMessage(common.getMessage());
        }
        if (customer != null) {
            vm.add(vmUtil.addErrorHtml(htmlEmail,
                    ResourceUtil.getLabel("home.label.register.validate.duplicate.email", locale)));
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
